package com.xishu.service;

import com.xishu.util.ClassUtil;
import com.xishu.util.JRedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Base64;

public class ListCacheService<T> {
    private static Logger logger = LoggerFactory.getLogger(ListCacheService.class);

    /**
     * 清除缓存
     *
     * @param shopId
     */
    public <T> void cleanCache(Long shopId, Class tclass) {
        String cacheKey = tclass.getName() + "." + shopId;
        JRedisUtil.delKV(cacheKey);
    }

    /**
     * 放缓存
     *
     * @param shopId
     * @param entity
     * @param <T>
     */
    public <T> void putCache(Long shopId, T entity) throws IOException {
        byte[] bytes = ClassUtil.getInstance().objectToBytes(entity);
        String objectByteArray = Base64.getEncoder().encodeToString(bytes);
        JRedisUtil.setKV(entity.getClass().getName() + "." + shopId, objectByteArray);
    }

    /**
     * 从缓存中获取对象
     *
     * @param shopId
     * @param tclass
     * @param <T>
     */
    public <T> T getCache(Long shopId, Class tclass) throws IOException, ClassNotFoundException {
        String cacheKey = tclass.getName() + "." + shopId;
        //先查询配置是否存在
        String entityValue = JRedisUtil.getKV(cacheKey);

        //找到了，反序列化
        if (entityValue != null) {
            byte[] objectByteArray = Base64.getDecoder().decode(entityValue);

            T entity = (T) ClassUtil.bytesToObject(objectByteArray);
            return entity;
        }

        return null;
    }
}
